package com.signway.module_signway_adapter_Api;

import android.content.Context;
import android.os.signwaymanager.SignwayManager;
import android.provider.Settings;
import android.util.Log;

import com.signway.open.api.IOpenSystemApi;
import com.signway.open.api.constant.ChangeOrientationConstant;
import com.signway.open.api.constant.SettingConstant;
import com.signway.utils.CommonTools;
import com.signway.utils.FileTools;
import com.signway.utils.LogHelper;
import com.signway.utils.SystemPropertiesInvoke;


import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2011-2019, by your Signway, All rights reserved.
 * -----------------------------------------------------------------
 *
 * ProjectName: droid5119
 *
 * Author: Administrator
 *
 * Email: pf.wang@Signway.cn
 *
 * Description:
 *
 * -----------------------------------------------------------------
 * 2019-5-29 : Create SignwaySystemApi.java
 * -----------------------------------------------------------------
 */
public class SignwaySystemApi implements IOpenSystemApi {

    private static final String TAG = "SignwaySystemApiBox3288";
    private static final String TEMP_SCREEN_SHOT_FILE_PATH = "/tmp/screen.png";
    private static SignwaySystemApi mSignwaySystemApi;
    private static Context mContext;
    private SignwayManager signwayManager;

    public static synchronized SignwaySystemApi getInstance(Context context) {
        mContext = context;
        if (mSignwaySystemApi == null) {
            mSignwaySystemApi = new SignwaySystemApi(context);
        }
        return mSignwaySystemApi;
    }

    public SignwaySystemApi(Context context) {
        this.mContext = context;
        signwayManager = SignwayManager.getInstance(mContext);
    }
    ScheduledExecutorService scheduledExecutorService = null;

    private SignwaySystemApi() {
    }

    //获取固件build.prop里的信息
    public String getSystemProperties(String key) {
        return getSystemProperties(key," ");
    }

    public String getSystemProperties(String key,String defaultValue) {
        String systemPropertiesInfo = "";;
        systemPropertiesInfo = SystemPropertiesInvoke.get(key,defaultValue);
        return systemPropertiesInfo;
    }


    public int getIntSystemProperties(String key) {
        int value = 0;

        try {
            value = Integer.parseInt(getSystemProperties(key));
        }catch (Exception e){
            value = 0;
        }

        return value;
    }

    //设置固件build.prop里的信息
    public void setSystemProperties(String key, String value) {
        SystemPropertiesInvoke.set(key,value);
    }

    //调用adb命令
    public void execRootCommand(String command) throws IOException {
        if (command == null) {
            LogHelper.w("command is null");
//            return null;
            return;
        }

        Runtime runtime = Runtime.getRuntime();
        Process proc = null;
//        if (Econfig.ECONFIG_SYSTEM_IS_FIRMWARE_5_1) {
        if (android.os.Build.VERSION.SDK_INT <= 22) {
            proc = runtime.exec(command);
        } else {
            proc = runtime.exec("su");

            OutputStream os = proc.getOutputStream();
            String cmd = command + "\n";
            os.write(cmd.getBytes());
            os.flush();
        }

//        return proc;
    }

    @Override
    public boolean format(int mount_type, Context context) {
        boolean ret = true;

        if (mount_type == SettingConstant.STORAGE_INLAY) {
            FileTools.delFolder("/mnt/sdcard/");
//            signwayManager.formatStorage("/mnt/sdcard/");

        } else if (mount_type == SettingConstant.STORAGE_SDDISK) {
//            signwayManager.formatStorage("/mnt/external_sd/");
            FileTools.delFolder("/mnt/external_sd/");

        } else if (mount_type == SettingConstant.STORAGE_UDISK) {
//            signwayManager.formatStorage("/mnt/usb_storage/");
            FileTools.delFolder("/mnt/usb_storage/");

        } else {
            ret = false;
        }

        return ret;
    }

    @Override
    public void setSystemTime(long time) {
//        signwayManager.setTime();
    }

    @Override
    public void setSystemTimeAuto(boolean isAuto) {
        signwayManager.setAutoTimeEnable(isAuto ?1:0);
    }

    @Override
    public void setSystemTimezoneAuto(boolean isAuto) {
//        signwayManager.setAutoTimeZoneOnoff(isAuto ?1:0);
    }

    @Override
    public boolean setPowerDeepStandby() {
        signwayManager.setDeepStandby();
        return false;
    }

    @Override
    public boolean setPowerDeepStandby(int time) {
       signwayManager.setDeepStandbyWakeTime(time * 60);
        return false;
    }

    //获取固件版本信息  主页面显示
    public String getAndroidVersion() {
        String systemVersion = getSystemProperties("ro.build.version.incremental");
        systemVersion = signwayManager.getFirmwareVersion();
        return systemVersion;
    }

    //获取固件版本信息  上传服务器
    public String getFirmwareVer() {
        String firmwareVer = "20170101";
        String ver = getSystemProperties("ro.build.version.incremental");
        if ((ver != null) && !"".equals(ver) /*&& ver.startsWith("chenwf.")*/ && ver.length() >= 15) {
            try {
                String[] value = ver.split("\\.");
                if (CommonTools.isMatchNumberPattern(value[value.length - 2]/*ver.substring(7, 15)*/)) {
                    firmwareVer = value[value.length - 2];//ver.substring(7, 15);
                }
            } catch (Exception e) {
                LogHelper.i("get firmware ver error: ");
            }
        }
        return firmwareVer;
    }

    /**
     * 固件升级时， 获取固件版本信息
     *
     * @return
     */
    public int getSystemVersion() {
        int and_ver_date = 0;
        final String android_ver = getSystemProperties("ro.build.version.incremental");
        LogHelper.i("android_ver: " + android_ver);
        int ver_pos = android_ver.lastIndexOf(".");
        if ((ver_pos != -1) && (ver_pos < android_ver.length())) {
            String date_ver = android_ver.substring(ver_pos - 8, ver_pos);
            LogHelper.i("date_ver: " + date_ver);
            try {
                and_ver_date = Integer.parseInt(date_ver);
            } catch (NumberFormatException ex) {

            }

            LogHelper.i("and_ver_date: " + and_ver_date);
        }
        return and_ver_date;
    }

    /*
     * 获取板卡信息
     * *** 板卡型号 0:5159  1:5161  2:5166 3:5168 4:5180 5:A20 6:others
     */
    public String getBoard() {
        int boardName = 0;
        String local_board = null;

        String buildUser; //编译账户
        String platForm;  //芯片名称
        buildUser = getSystemProperties("ro.build.user");
        platForm = getSystemProperties("ro.board.platform");
        LogHelper.i("buildUser--->" + buildUser);
        LogHelper.i("platForm--->" + platForm);
        if (buildUser.equals("chenwf")) {
            if (platForm.equals("rk30xx")) {
                boardName = 0;  //5159
            } else if (platForm.equals("rk3188")) {
                //5161与5166芯片同为rk3188 进一步区分
                File nodeFile = new File("/proc/asound/RK29RK1000");
                if (nodeFile.exists()) {
                    boardName = 1;
                } else {
                    boardName = 2;
                }
            } else if (platForm.equals("madison")) {
                boardName = 3;  //5168
            } else if (platForm.equals("rk3288")) {
                boardName = 4;  //5180
            } else if (platForm.equals("wing")) {
                boardName = 5;  //A20
            } else if (platForm.equals("rk312x")) {
                boardName = 7; //5119
            }
        } else {
            boardName = 6;  //others
        }

        switch (boardName) {
            case 0:
                local_board = "5159";
                break;
            case 1:
                local_board = "5161";
                break;
            case 2:
                local_board = "5166";
                break;
            case 3:
                local_board = "5168";
                break;
            case 4:
                local_board = "BOX3288";
                break;
            case 5:
                local_board = "A20";
                break;
            case 6:
                local_board = "others";
                break;
            case 7:
                local_board = "5119";
                break;

        }
        return local_board;
    }

    /**
     * 读取固件参数，判断是否是上电开机
     * true:第一次上电  false:已经开机
     *
     * @return
     */
    public boolean getPowerUp() {
//        String powerUp = getSystemProperties("ro.sf.powerup");
//        LogUtil.i("check power up: " + powerUp);
//        if (powerUp.equals("true")) {
//            return true;
//        } else {
//            return false;
//        }
        return true;
    }

    /**
     * 设置上电已经开机
     */
    public void setPowerUp() {
        setSystemProperties("ro.sf.powerup", "false");
    }

    /**
     * 读取固件参数，判断是否启动TestAPP
     * true:需要  false:不需要
     *
     * @return
     */
    public boolean getIsOpenTestApp() {
//        int KEY_VALUE_TEST_APP_START = 1;
//        Eeprom eeprom = new Eeprom();
//        String appMode = getSystemProperties("sys.default.appmode");
//        byte[] buffEeprom = new byte[1];
//        eeprom.ReadEepromInfo(0x62, buffEeprom, buffEeprom.length);
//        LogUtil.i("appMode:" + appMode + ", eeprom " + buffEeprom[0]);
//        if(appMode == null){
//            return false;
//        }
//        // appMode值为1; Eeprom[0]不是0x03;
//        if (appMode.equals(KEY_VALUE_TEST_APP_START) || buffEeprom[0] != 0x03) {
//            return true;
//        }
        return false;
    }

    /**
     * 设置系统喂狗
     * apk启动，先关闭系统喂狗，再打开apk喂狗
     * apk退出，先关闭apk喂狗，再打开系统喂狗
     * set  true：打开    false：关闭
     * <p>
     * sys.firmware.watchdog  enable disable exit
     */
    public void setSystemWatchDog(boolean set) {

      signwayManager.setApkWatchdogEnable(set ? 1 : 0);
        startWatchDog();
    }

    @Override
    public void startWatchDog() {

        if (scheduledExecutorService == null){
            scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        }
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG,"---Feed Watchdog---");
                feedWatchDog();
            }
        }, 10, 30, TimeUnit.SECONDS);
    }

    @Override
    public void stopWatchDog() {
        setSystemWatchDog(false);
        if (scheduledExecutorService != null){
            scheduledExecutorService.shutdownNow();
        }

    }

    @Override
    public void feedWatchDog() {

        signwayManager.feedWatchdog();
    }

    /**
     * 获取屏幕当前旋转角度
     *
     * @return
     */
    public int getOrientation() {
        //        int rotation = getIntSystemProperties("ro.sf.hwrotation");
        int rotation = 0;
        rotation = signwayManager.getRotationScreen();
        LogHelper.d("rotation = " + rotation);
        if (rotation == 270) {
            return ChangeOrientationConstant.Orientation.REVERSE_PORTRAIT;
        } else if (rotation == 180) {
            return ChangeOrientationConstant.Orientation.REVERSE_LANDSCAPE;
        } else if (rotation == 90) {
            return ChangeOrientationConstant.Orientation.PORTRAIT;
        } else {
            return ChangeOrientationConstant.Orientation.LANDSCAPE;
        }
    }

    /**
     * 设置屏幕旋转角度
     *
     * @param orientation
     * @param context
     */
    public void setOrientation(int orientation, Context context) {
        //        WindowManager mWindow = (WindowManager) (context.getSystemService(Context.WINDOW_SERVICE));

//        String str_hwrotation = new String("ro.sf.hwrotation");
        int rotation = 0;
        switch (orientation) {
            case ChangeOrientationConstant.Orientation.LANDSCAPE: // 0
//                mWindow.setSystemProp(str_hwrotation, "0");
                rotation = 0;
                break;
            case ChangeOrientationConstant.Orientation.PORTRAIT: // 90
//                mWindow.setSystemProp(str_hwrotation, "270");
                rotation = 90;
                break;
            case ChangeOrientationConstant.Orientation.REVERSE_LANDSCAPE: // 180
//                mWindow.setSystemProp(str_hwrotation, "180");
                rotation = 180;
                break;
            case ChangeOrientationConstant.Orientation.REVERSE_PORTRAIT: // 270
//                mWindow.setSystemProp(str_hwrotation, "90");
                rotation = 270;
                break;
            default:
                break;

        }
       signwayManager.setRotationScreen(rotation);
    }

    /**
     * 获取sn号
     *
     * @return
     */
    public String getSerial() {
        String sn = "";
         sn = signwayManager.getSN();
        LogHelper.d("getsn info ==" + sn);
        return sn;
    }

    public boolean isReadSerial() {
        return true;
//        return SNInfoOperation.getInstance().isReadSN();
    }

    /**
     * 截屏
     *
     * @param filename
     * @return
     */
    public boolean screenShot(String filename) {
        LogHelper.d("screenShot filename = " + filename);
        signwayManager.takeScreenshot(filename,0);
        return true;
    }

    /**
     * 截屏
     *
     * @param filename
     * @return
     */
    public boolean screenShot(String filename, int screenType) {
        LogHelper.d("screenShot filename = " + filename + "; screenType = " + screenType);
        signwayManager.takeScreenshot(filename, screenType);
        return true;
    }

    public boolean getSystemNavigationStatus(Context context){
        boolean isShow = false;
        int status = Settings.System.getInt(context.getContentResolver(),
                "droid_5159_hide_systemBar", 1);
        isShow = (status != 0) ? true: false;
        return isShow;
    }

    /**
     * 隐藏或者显示系统下面的导航栏 true为显示。false为隐藏
     *
     * @param flag
     */
    public void operateSystemNavigation(boolean flag, Context context) {
        //        Intent intent = new Intent("rk.android.systemBar.SHOW");
//        intent.putExtra("display", flag);
//        context.sendBroadcast(intent);
      signwayManager.hideStatusBar(flag);
    }

    /**
     * 获取运行内存容量
     */
    public String getRunningMemory() {

        String ddr = signwayManager.getRunningMemory();

        LogHelper.i(TAG, "--->system ddr:" + ddr);
        return ddr;
    }

    /**
     * 获取内部存储容量
     */
    public float getInternalStorageMemory() {
//        StatFs stat;
//        UsbMonitorUtil.checkUsbExist();
//
//        if (FileUtil.MOUNT_TYPE == SettingConstant.STORAGE_INLAY) {
//            stat = new StatFs(FileUtil.PATH_LOCAL);
//        } else if (FileUtil.MOUNT_TYPE == SettingConstant.STORAGE_UDISK) {
//            stat = new StatFs(UsbMonitorUtil.usbPath);
//        } else {
//            stat = new StatFs(UsbMonitorUtil.sdPath);
//        }
//
//        long blockSize = stat.getBlockSize();
//        long blocks = stat.getBlockCount();
//        float all = blocks * blockSize;
//        LogUtil.d("sdcard all" + all);
//        return all;
        return 0;
    }


    public long getLastTouchTime(){
        long lastTouchTime = 0;
//        try {
//            IWindowManager mWindowManager = IWindowManager.Stub
//                    .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
//            lastTouchTime = mWindowManager.getLastTouchTime();
//        } catch (RemoteException e) {
//            Log.e(TAG, "no getLastTouchTime api error:" + e.toString());
//        } catch (Exception e){
//            Log.e(TAG, "no getLastTouchTime api error:" + e.toString());
//        }
        return lastTouchTime;
    }

}
